package com.tianqu.tms.www.rental.controller;

import java.io.File;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TmsController;
import com.tianqu.tms.core.base.TxController;
import com.tianqu.tms.core.base.UserContext;
import com.tianqu.tms.core.exception.TmsException;
import com.tianqu.tms.core.exception.TransactionException;
import com.tianqu.tms.core.security.TmsUserProfile;
import com.tianqu.tms.core.util.CopyFile;
import com.tianqu.tms.core.util.DateUtil;
import com.tianqu.tms.core.util.ImageUtils;
import com.tianqu.tms.core.util.Registry;
import com.tianqu.tms.core.util.StringUtil;
import com.tianqu.tms.core.util.TmsConstants;
import com.tianqu.tms.entity.CarImage;
import com.tianqu.tms.entity.RentalContractInfo;
import com.tianqu.tms.entity.RentalLocationInfo;
import com.tianqu.tms.www.rental.actionform.RentalContractAddInputForm;
import com.tianqu.tms.www.rental.viewhelper.RentalContractAddInputViewHelper;


/**
 * 合同查询/修改-添加确认 controller
 * @author mufeiyu
 *
 */
public class RentalContractSearchAddResultController extends TmsController {
	private Logger logger = Logger.getLogger(RentalContractSearchAddResultController.class);
	private String Serial = null;
	private int cId = 0;
	private String sysPath = null;
	@Override
	public void execute(UserContext uc) throws Exception {
		logger.debug(this.getClass().getName() + "#execute was called.");
		
		TxController controller = TxController.getTxController();
		RentalContractAddInputViewHelper viewHelper = (RentalContractAddInputViewHelper) uc.getAttribute(TmsConstants.VIEWHELP);

		// 添加事务提交异常捕获
		try {
			controller.begin();
			sysPath = (String) uc.getAttribute("sysPath");
			Serial = viewHelper.getSerial();
			RentalContractAddInputForm rentalForm = (RentalContractAddInputForm) uc.getInputForm();			
			RentalContractInfo contractInfo = RentalContractInfo.getInstance();
			RentalContractInfo oldContractInfo = contractInfo.searchRentalContractDetailInfo(rentalForm.getId());
			
			contractInfo = getContractInfo(viewHelper);
			contractInfo.setId(rentalForm.getId());
			TmsUserProfile profile = uc.getUserProfile();	
			
			contractInfo.setUpdateUserId(profile.getUniqueId());		
						
			// 更新市场租位合同信息表
			contractInfo.updateContractInfo(contractInfo,rentalForm.getSerialHold());
			uc.setAttribute("serialsave", contractInfo.getSerial());

			// 插入 租赁合同操作记录表
			String remark = getRemark(oldContractInfo,contractInfo);
			contractInfo.setRemark(remark);
			contractInfo.setHandleType(2);//2：合同修改
			contractInfo.insertContractUpdateHistroy(contractInfo);
			
			cId = (int)contractInfo.getId();
			CarImage carImg = CarImage.getInstance();
			/**
			 * 插入图片信息
			 */
			carImg.insertCarImages(getcarInage(viewHelper));		
			controller.commit();
			
		} catch (Exception e) {
			try {
				controller.rollback();
			} catch (TransactionException e1) {
				throw new TmsException(TmsException.DB_TXCRROR, e1);
			}
			// 系统异常
			if (e instanceof TmsException) {
				throw e;
			}
			throw new TmsException(TmsException.DB_TXCRROR, e);
		}
	}
	/**
	 * 图片信息
	 * 
	 * @param view
	 * @return
	 */
	private List<CarImage> getcarInage(RentalContractAddInputViewHelper view) {
		List<CarImage> list = new ArrayList<CarImage>();
		if (!StringUtil.isNullOrBlank(view.getPhoto_1())) {
			list.add(carImage(1,view.getPhoto_1()));
			imageUpLoad(view.getPhoto_1(), imagePath(1,view.getPhoto_1()));
		}
		if (!StringUtil.isNullOrBlank(view.getPhoto_2())) {
			list.add(carImage(2,view.getPhoto_2()));
			imageUpLoad(view.getPhoto_2(), imagePath(2,view.getPhoto_2()));
		}
		if (!StringUtil.isNullOrBlank(view.getPhoto_3())) {
			list.add(carImage(3,view.getPhoto_3()));
			imageUpLoad(view.getPhoto_3(), imagePath(3,view.getPhoto_3()));
		}
		if (!StringUtil.isNullOrBlank(view.getPhoto_4())) {
			list.add(carImage(4,view.getPhoto_4()));
			imageUpLoad(view.getPhoto_4(), imagePath(4,view.getPhoto_4()));
		}
		if (!StringUtil.isNullOrBlank(view.getPhoto_5())) {
			list.add(carImage(5,view.getPhoto_5()));
			imageUpLoad(view.getPhoto_5(), imagePath(5,view.getPhoto_5()));
		}
		if (!StringUtil.isNullOrBlank(view.getPhoto_6())) {
			list.add(carImage(6,view.getPhoto_6()));
			imageUpLoad(view.getPhoto_6(), imagePath(6,view.getPhoto_6()));
		}
		if (!StringUtil.isNullOrBlank(view.getPhoto_7())) {
			list.add(carImage(7,view.getPhoto_7()));
			imageUpLoad(view.getPhoto_7(), imagePath(7,view.getPhoto_7()));
		}
		if (!StringUtil.isNullOrBlank(view.getPhoto_8())) {
			list.add(carImage(8,view.getPhoto_8()));
			imageUpLoad(view.getPhoto_8(), imagePath(8,view.getPhoto_8()));
		}
		return list;
	}
	/**
	 * 图片类
	 * 
	 * @param value
	 * @return
	 */
	private CarImage carImage(int key,String imgPath) {
		CarImage carImage = new CarImage();
		carImage.setcId(cId);
		carImage.setImgKey(String.valueOf(key));
		carImage.setImgPath(ImageUtils.getImageUrl(
				Registry.getConfig(TmsConstants.UPLOAD_RENTAL_IMAGE_PATCH_KEY) + Serial + "/"
				+ imagePath(key,imgPath)));
		carImage.setImgSrc(3);
		carImage.setImgType(String.valueOf(1));
		return carImage;
	}
	/**
	 * 将图片上传到服务器
	 */
	private void imageUpLoad(String Path, String ImageName) {

		sysPath = sysPath.replace("\\tmsweb", "");
		File infoFile = new File(sysPath + Path);
		File outFile = new File(ImageUtils.getImageDirectoryPath(Registry.getConfig(TmsConstants.UPLOAD_RENTAL_IMAGE_PATCH_KEY) + Serial + "/") + ImageName);
		CopyFile.copy(infoFile, outFile);
	}
	/**
	 * 图片名称
	 * 
	 * @param Key
	 * @return
	 */
	private String imagePath(int Key,String imgPath) {
		String a = "1";
		String k = String.valueOf(Key);
		String t = "3";
		return this.Serial + a + k + t + getImgFormat(imgPath);
	}
	/**
	 * 图片后缀
	 * 
	 * @param imgPath
	 * @return
	 */
	public String getImgFormat(String imgPath) {
		int i = 0;
		if(imgPath.length()==0)return "";
		while (i != -1) {
			// 找到上传文件的类型的位置，这个地方的是'.'
			i = imgPath.indexOf(".");
			/* 截取上传文件的后缀名,此时得到了文件的类型 */
			imgPath = imgPath.substring(i+1).toLowerCase();
		}
		imgPath = "." + imgPath;
		return imgPath;
	}

	/**
	 * 市场租赁合同
	 * 
	 * @param view
	 * @return
	 * @throws ParseException 
	 */
	private RentalContractInfo getContractInfo(RentalContractAddInputViewHelper view) throws ParseException{
		RentalContractInfo contractInfo = new RentalContractInfo();
		//合同信息
		contractInfo.setSerial(view.getSerial());
		contractInfo.setRent(Integer.parseInt(view.getRent().replaceAll(",", "")));
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式 
		contractInfo.setStartDate(new Timestamp(df.parse(view.getStartDate()).getTime()));
		contractInfo.setEndDate(new Timestamp(df.parse(view.getEndDate()).getTime()));
		contractInfo.setLocationSerial(view.getLocationSerial());

		//合同开始的日期
		Date startDate = df.parse(view.getStartDate());
		Date endDate = df.parse(view.getEndDate());
		// 今天的日期
		Date currentDate = df.parse(df.format(new Date(System.currentTimeMillis())));				
		// 比较
		if (startDate.compareTo(currentDate) <= 0 && endDate.compareTo(currentDate) > 0) {
			contractInfo.setStatus(2);
		} else if (endDate.compareTo(currentDate) <= 0) {
			contractInfo.setStatus(3);
		} else if (startDate.compareTo(currentDate) > 0) {
			contractInfo.setStatus(1);
		}
		
		//合同人信息
		contractInfo.setOwnerName(view.getOwnerName());
		contractInfo.setOwnerIdCardNo(view.getOwnerIdCardNo());
		if(view.getOwnerSex().equals("女"))
		{
			contractInfo.setOwnerSex(2);
		} else {
			contractInfo.setOwnerSex(1);
		}		
		contractInfo.setOwnerBirthday(new Timestamp(df.parse(view.getOwnerBirthday()).getTime()));
		contractInfo.setOwnerPhone(view.getOwnerPhone());
		contractInfo.setOwnerAddress(view.getOwnerAddress());
		contractInfo.setRemark(view.getRemark());
		//图片信息
		contractInfo.setPhoto_1(view.getPhoto_1());
		contractInfo.setPhoto_2(view.getPhoto_2());
		contractInfo.setPhoto_3(view.getPhoto_3());
		contractInfo.setPhoto_4(view.getPhoto_4());
		contractInfo.setPhoto_5(view.getPhoto_5());
		contractInfo.setPhoto_6(view.getPhoto_6());
		contractInfo.setPhoto_7(view.getPhoto_7());
		contractInfo.setPhoto_8(view.getPhoto_8());
		return contractInfo;
	}
	
	private String getRemark (RentalContractInfo oldContractInfo,RentalContractInfo newContractInfo) {
		StringBuffer remark = new StringBuffer();
		boolean flg = false;
		
		if(null != oldContractInfo && null != newContractInfo) {
			// 租金(元)
			if (oldContractInfo.getRent() != newContractInfo.getRent()) {
				if (flg) {
					remark.append("；");
				} else {
					flg = true;
				}
				
				remark.append("租金(元)从").append(oldContractInfo.getRent()).append("修改为").append(newContractInfo.getRent());
			}
			
			// 合同开始日期
			if (!DateUtil.DateToString11(oldContractInfo.getStartDate()).equals(DateUtil.DateToString11(newContractInfo.getStartDate()))) {
				if (flg) {
					remark.append("；");
				} else {
					flg = true;
				}
				
				remark.append("合同开始日期从").append(DateUtil.DateToString11(oldContractInfo.getStartDate())).append("修改为").append(DateUtil.DateToString11(newContractInfo.getStartDate()));
			}
			
			
			// 合同结束日期
			if (!DateUtil.DateToString11(oldContractInfo.getEndDate()).equals(DateUtil.DateToString11(newContractInfo.getEndDate()))) {
				if (flg) {
					remark.append("；");
				} else {
					flg = true;
				}
				
				remark.append("合同结束日期从").append(DateUtil.DateToString11(oldContractInfo.getEndDate())).append("修改为").append(DateUtil.DateToString11(newContractInfo.getEndDate()));
			}
			
			// 租位编号
			if (!oldContractInfo.getLocationSerial().equals(newContractInfo.getLocationSerial())) {
				if (flg) {
					remark.append("；");
				} else {
					flg = true;
				}
				
				remark.append("租位编号从").append(oldContractInfo.getLocationSerial()).append("修改为").append(newContractInfo.getLocationSerial());
			}
			
			// 合同人姓名
			if (!oldContractInfo.getOwnerName().equals(newContractInfo.getOwnerName())) {
				if (flg) {
					remark.append("；");
				} else {
					flg = true;
				}
				
				remark.append("合同人姓名从").append(oldContractInfo.getOwnerName()).append("修改为").append(newContractInfo.getOwnerName());
			}
			
			// 身份证号码
			if (!oldContractInfo.getOwnerIdCardNo().equals(newContractInfo.getOwnerIdCardNo())) {
				if (flg) {
					remark.append("；");
				} else {
					flg = true;
				}
				
				remark.append("身份证号码从").append(oldContractInfo.getOwnerIdCardNo()).append("修改为").append(newContractInfo.getOwnerIdCardNo());
			}
			
			// 性别
			if (oldContractInfo.getOwnerSex() != newContractInfo.getOwnerSex()) {
				if (flg) {
					remark.append("；");
				} else {
					flg = true;
				}
				remark.append("性别从");
				if (oldContractInfo.getOwnerSex() == 1) {
					remark.append("男").append("修改为");
				} else {
					remark.append("女").append("修改为");
				}
				
				if (newContractInfo.getOwnerSex() == 1) {
					remark.append("男");
				} else {
					remark.append("女");
				}
			}
			
			// 出生日期
			if (!DateUtil.DateToString11(oldContractInfo.getOwnerBirthday()).equals(DateUtil.DateToString11(newContractInfo.getOwnerBirthday()))) {
				if (flg) {
					remark.append("；");
				} else {
					flg = true;
				}
				
				remark.append("出生日期从").append(DateUtil.DateToString11(oldContractInfo.getOwnerBirthday())).append("修改为").append(DateUtil.DateToString11(newContractInfo.getOwnerBirthday()));
			}
			
			// 联系电话
			if (!oldContractInfo.getOwnerPhone().equals(newContractInfo.getOwnerPhone())) {
				if (flg) {
					remark.append("；");
				} else {
					flg = true;
				}
				remark.append("联系电话从").append(oldContractInfo.getOwnerPhone()).append("修改为").append(newContractInfo.getOwnerPhone());
			}
			
			// 地址
			if (!oldContractInfo.getOwnerAddress().equals(newContractInfo.getOwnerAddress())) {
				if (flg) {
					remark.append("；");
				} else {
					flg = true;
				}
				
				remark.append("地址从").append(oldContractInfo.getOwnerAddress()).append("修改为").append(newContractInfo.getOwnerAddress());
			}
			
			// 资料1
			if (!oldContractInfo.getPhoto_1().equals(newContractInfo.getPhoto_1())) {
				if (flg) {
					remark.append("；");
				} else {
					flg = true;
				}
				
				if (StringUtil.isNullOrBlank(oldContractInfo.getPhoto_1()))
					remark.append("资料1从无").append("修改为").append(newContractInfo.getPhoto_1());
				else
					remark.append("资料1从").append(oldContractInfo.getPhoto_1()).append("修改为").append(newContractInfo.getPhoto_1());
			}
			// 资料2
			if (!oldContractInfo.getPhoto_2().equals(newContractInfo.getPhoto_2())) {
				if (flg) {
					remark.append("；");
				} else {
					flg = true;
				}
				
				if (StringUtil.isNullOrBlank(oldContractInfo.getPhoto_2()))
					remark.append("资料2从无").append("修改为").append(newContractInfo.getPhoto_2());
				else
				remark.append("资料2从").append(oldContractInfo.getPhoto_2()).append("修改为").append(newContractInfo.getPhoto_2());
			}
			
			// 资料3
			if (!oldContractInfo.getPhoto_3().equals(newContractInfo.getPhoto_3())) {
				if (flg) {
					remark.append("；");
				} else {
					flg = true;
				}
			
				if (StringUtil.isNullOrBlank(oldContractInfo.getPhoto_3()))
					remark.append("资料3从无").append("修改为").append(newContractInfo.getPhoto_3());
				else
					remark.append("资料3从").append(oldContractInfo.getPhoto_3()).append("修改为").append(newContractInfo.getPhoto_3());
			}
			
			// 资料4
			if (!oldContractInfo.getPhoto_4().equals(newContractInfo.getPhoto_4())) {
				if (flg) {
					remark.append("；");
				} else {
					flg = true;
				}
				
				if (StringUtil.isNullOrBlank(oldContractInfo.getPhoto_4()))
					remark.append("资料4从无").append("修改为").append(newContractInfo.getPhoto_4());
				else
					remark.append("资料4从").append(oldContractInfo.getPhoto_4()).append("修改为").append(newContractInfo.getPhoto_4());
			}
			
			// 资料5
			if (!oldContractInfo.getPhoto_5().equals(newContractInfo.getPhoto_5())) {
				if (flg) {
					remark.append("；");
				} else {
					flg = true;
				}
				
				if (StringUtil.isNullOrBlank(oldContractInfo.getPhoto_5()))
					remark.append("资料5从无").append("修改为").append(newContractInfo.getPhoto_5());
				else
					remark.append("资料5从").append(oldContractInfo.getPhoto_5()).append("修改为").append(newContractInfo.getPhoto_5());
			}
			
			// 资料6
			if (!oldContractInfo.getPhoto_6().equals(newContractInfo.getPhoto_6())) {
				if (flg) {
					remark.append("；");
				} else {
					flg = true;
				}
				
				if (StringUtil.isNullOrBlank(oldContractInfo.getPhoto_6()))
					remark.append("资料6从无").append("修改为").append(newContractInfo.getPhoto_6());
				else
					remark.append("资料6从").append(oldContractInfo.getPhoto_6()).append("修改为").append(newContractInfo.getPhoto_6());
			}
			
			// 资料7
			if (!oldContractInfo.getPhoto_7().equals(newContractInfo.getPhoto_7())) {
				if (flg) {
					remark.append("；");
				} else {
					flg = true;
				}

				if (StringUtil.isNullOrBlank(oldContractInfo.getPhoto_7()))
					remark.append("资料7从无").append("修改为").append(newContractInfo.getPhoto_7());
				else
					remark.append("资料7从").append(oldContractInfo.getPhoto_7()).append("修改为").append(newContractInfo.getPhoto_7());
			}
			
			// 资料8
			if (!oldContractInfo.getPhoto_8().equals(newContractInfo.getPhoto_8())) {
				if (flg) {
					remark.append("；");
				} else {
					flg = true;
				}
				
				if (StringUtil.isNullOrBlank(oldContractInfo.getPhoto_8()))
					remark.append("资料8从无").append("修改为").append(newContractInfo.getPhoto_8());
				else
					remark.append("资料8从").append(oldContractInfo.getPhoto_8()).append("修改为").append(newContractInfo.getPhoto_8());
			}
		}
		
		return remark.toString();
	}
}
